import { Card, Steps, Typography, Popover, Row, Col, Input, Form, Select, DatePicker, Cascader, Upload, Modal, Alert, Button, Space, Descriptions, Collapse } from 'antd'
import React, { useState, useEffect } from 'react'
// import ActivityGraph from './ActivityGraph/ActivityGraph';
// import Thumbnail from "./Thumbnail/Thumbnail"
import moment from 'moment'; //时间
import { PlusOutlined, DeleteOutlined, CaretRightOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import ImgCrop from 'antd-img-crop';
import TextLoop from 'react-text-loop';
import "./ActivityPlan.less"
import x from "../components/下载.png"
import Apply from './Apply';
import Vote from "./Vote"
import SignIn from './SignIn';
import Tickets from './Tickets';
import LuckyDraw from './LuckyDraw';
import { result } from 'lodash';
// import EstablishPrev from './EstablishPrev';
// import EstablishNext from './EstablishNext'
const { Title } = Typography
const { Step } = Steps;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Panel } = Collapse;
const { confirm } = Modal;
function ActivityPlan() {
    const customDot = (dot, { status, index }) => (
        <Popover>
            {dot}
        </Popover>
    );
    const validateMessages = {
        required: '请输入${label}',
        types: {
            email: '${label} is not a valid email!',
            number: '${label} is not a valid number!',
        },
        number: {
            range: '${label} must be between ${min} and ${max}',
        },
    };
    const onFinish = (values) => {
        console.log('Success:', values);
    };

    // 缩略图
    function getBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });
    }
    // 图片裁剪
    const [previewVisible, setpreviewVisible] = useState(false)
    const [previewImage, setpreviewImage] = useState('')
    const [previewTitle, setpreviewTitle] = useState('')
    const [fileList, setfileList] = useState([])
    const [thumbnailVisible, setthumbnailVisible] = useState(false)
    const [thumbnailImage, setthumbnailImage] = useState('')
    const [thumbnailTitle, setthumbnailTitle] = useState('')
    const [thumbnailfileList, setthumbnailfileList] = useState([])
    const [aspect, setAspect] = useState(400 / 109);
    const handleCancel = () => {
        setpreviewVisible(false)
    };
    const handleCancels = () => setthumbnailVisible(false);
    const handlePreview = async file => {
        console.log("file---------------------------75", file)
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setpreviewImage(file.url || file.preview)
        setpreviewVisible(true)
        setpreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1))
    };

    function handleChange({ fileList }) {
        setfileList(fileList)
    }
    // 缩略图
    function thumbnailfileChange({ fileList }) {
        setthumbnailfileList(fileList)
    }
    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const [current, setCurrent] = useState(1);
    const next = () => {
        form.validateFields().then(value => {
            setCurrent(prevcurrent => prevcurrent + 2);
            setfromShow(false)
        }).catch(errors => {
            console.log("109-----------", errors)

        })
    };
    const prev = () => {
        setCurrent(current - 2);
        setfromShow(true)
    };
    const choice = [
        { id: 1, title: "报名", active: false, context: <Apply /> },
        { id: 2, title: "投票", active: false, context: <Vote /> },
        { id: 3, title: "门票", active: false, context: <Tickets /> },
        { id: 4, title: "签到", active: false, context: <SignIn /> },
        { id: 5, title: "抽奖", active: false, context: <LuckyDraw /> }
    ]
    const [choices, setchoices] = useState(choice)  //初始化-
    const [newchoice, setnewchoice] = useState([])   //新的数组  true
    const [activityId, setActivityId] = useState();
    // 点击取消
    const changeSelect = (id, index) => {
        setActivityId(id);
        const data = choices.find((item) => id == item.id);
        if (data.active) {
            showConfirm()
        } else {
            choiceClick(index, data);
        }
    };
    // 
    const choiceClick = (index, data) => {
        data.active = !data.active;
        choices.splice(index, 1, data);
        setchoices(choices);
        const newObj = choices.filter((item, index, array) => {
            return item.active;
        });
        setnewchoice(newObj);
    }
    // 模态框
    function showConfirm() {
        confirm({
            title: 'Do you Want to delete these items?',
            icon: <ExclamationCircleOutlined />,
            content: 'Some descriptions',
            onOk() {
                console.log('OK');
                const data = choices.find((item) => item.id == activityId);
                const index = choices.findIndex((item) => item.id == activityId);
                choiceClick(index, data);
            },
            onCancel() {
                console.log('Cancel');
            },
        });
    }
    // 切换表单
    const [fromShow, setfromShow] = useState(true)
    // 折叠面板
    const [isShow, setisShow] = useState(true)
    const panelChange = () => {
        setisShow(false)
    }
    // 限制时间
    function disabledDate(current) {
        // Can not select days before today and today
        // console.log(current)
        return current && current <= moment().startOf('day');
    }
    function disabledDateTime() {
        return {
            disabledHours: () => range(0, 24).splice(4, 20),
            disabledMinutes: () => range(30, 60),
            disabledSeconds: () => [55, 56],
        };
    }
    function range(start, end) {
        const result = [];
        for (let i = start; i < end; i++) {
            result.push(i);
        }
        return result;
    }

    const [form] = Form.useForm()
    useEffect(() => {
        // 把图片的信息赋值给 values
        form.setFieldsValue({
            activitymap: fileList,
            thumbnail: thumbnailfileList
        }, [fileList, thumbnailfileList])
    })
    const options = [
        {
            value: 'zhejiang',
            label: 'Zhejiang',
            children: [
                {
                    value: 'hangzhou',
                    label: 'Hangzhou',
                },
            ],
        },
        {
            value: 'jiangsu',
            label: 'Jiangsu',
            children: [
                {
                    value: 'nanjing',
                    label: 'Nanjing',
                },
            ],
        },
    ];
    return (
        <div className="activityPlan-box">
            <Card className="activityPlan-box-card">
                <Title level={4}>创建活动</Title>
                <Steps current={current} progressDot={customDot}>
                    <Step title="基本信息" />
                    <Step title />
                    <Step title="活动信息" />
                </Steps>
            </Card>
            <div className={fromShow ? 'steps-content ' : 'fromIsShow'}>
                <Card className="activityPlan-box-card">
                    <Title level={5}
                        className="first-desc"
                    >请填写基本信息</Title>
                    <Form
                        form={form}
                        id="activityFrom"
                        validateMessages={validateMessages}
                        layout='vertical'
                        wrapperCol={{
                            span: 8,
                        }}
                        // onFinishFailed={onFinishFailed}
                        onFinish={onFinish}
                    >
                        <Row>
                            <Col span={9}>
                                <Form.Item
                                    name="name"
                                    label="活动名称"
                                    rules={[{ required: true }]}
                                >
                                    <Input
                                        placeholder='请输入活动名称'
                                        className='activityPlan-box-card-input' />

                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="citys"
                                    label="地区选择"
                                    rules={[{ required: true }]}
                                >
                                    <Cascader
                                        options={options}
                                        // onChange={onChange}
                                        placeholder="请选择活动所属地区"
                                        className='activityPlan-box-card-input'
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="range-time-picker"
                                    label="活动时间"
                                    rules={[{ required: true }]}
                                >
                                    <RangePicker
                                        format="YYYY-MM-DD HH:mm:ss"
                                        disabledDate={disabledDate}
                                        disabledTime={disabledDateTime}
                                        showTime={{ defaultValue: moment('00:00:00', 'HH:mm:ss') }}
                                        className='activityPlan-box-card-input'
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="city"
                                    label="活动地点"
                                >
                                    <Input placeholder='请输入活动地点' className='activityPlan-box-card-input' />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="sponsor"
                                    label="活动主办方"
                                >
                                    <Input
                                        placeholder='请输入活动主办方'
                                        className='activityPlan-box-card-input' />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="activitycontext"
                                    label="活动内容"
                                    rules={[{ required: true }]}
                                >
                                    <TextArea
                                        placeholder='活动内容'
                                        className='activityPlan-box-card-input'
                                        style={{ maxHeight: "160px" }} />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Form.Item
                                    name="activitymap"
                                    label="活动图"
                                    rules={[{ required: true }]}
                                    valuePropName="fileList"
                                    className="activitymap"
                                >
                                    <ImgCrop rotate aspect={aspect}>
                                        <Upload
                                            name="fils"
                                            style={{ width: '410px' }}
                                            // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                            listType="picture-card"
                                            fileList={fileList}
                                            onPreview={handlePreview}
                                            onChange={handleChange}
                                        >
                                            {fileList.length >= 1 ? null : uploadButton}
                                        </Upload>
                                    </ImgCrop>
                                    <Modal
                                        style={{ width: '410px' }}
                                        visible={previewVisible}
                                        title={previewTitle}
                                        footer={null}
                                        onCancel={handleCancel}
                                    >
                                        <img
                                            alt="example"
                                            style={{ width: '100%' }}
                                            src={previewImage} />
                                    </Modal>
                                    <Alert
                                        className="xinxin"
                                        style={{ background: "none" }}
                                        banner
                                        message={
                                            <TextLoop mask>
                                                <span>建议尺寸：1035*261</span>
                                            </TextLoop>
                                        }
                                    />
                                </Form.Item>
                            </Col>

                            {/* 缩略图、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、 */}
                            <Col span={9}>
                                <Form.Item
                                    name="thumbnail"
                                    label="缩略图"
                                    rules={[{ required: true }]}
                                >
                                    <div className="activityPlan-box-thumbnail">
                                        <ImgCrop >
                                            <Upload
                                                name="files"
                                                // action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                                                listType="picture-card"
                                                fileList={thumbnailfileList}
                                                onPreview={handlePreview}
                                                onChange={thumbnailfileChange}
                                                style={{ width: "100px", height: "100px" }}
                                            >
                                                {thumbnailfileList.length >= 1 ? null : uploadButton}
                                            </Upload>
                                            <Modal
                                                visible={thumbnailVisible}
                                                title={thumbnailTitle}
                                                footer={null}
                                                onCancel={handleCancels}
                                            >
                                                <img alt="example" src={thumbnailImage} />
                                            </Modal>

                                        </ImgCrop>
                                    </div>
                                    <Alert
                                        style={{ background: "none" }}
                                        banner
                                        message={
                                            <TextLoop mask>
                                                <span>建议尺寸：168*261</span>
                                            </TextLoop>
                                        }
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={9}>
                                <Title
                                    className="first-desc"
                                    level={5}>请编写活动日常规划 <span className="first-desc-span">(可添加多条)</span></Title>

                                <Form.Item
                                    // name="Actname"
                                    label="日程名称"
                                >
                                    <Form.List name="Actschedule">
                                        {(fields, { add, remove }) => (
                                            <>
                                                {fields.map(field => (
                                                    <Space
                                                        key={field.key}
                                                        style={{ display: 'flex', marginBottom: 8 }}
                                                        align="baseline">
                                                        <Form.Item
                                                            {...field}
                                                            name={[field.name, 'first']}
                                                            fieldKey={[field.fieldKey, 'first']}
                                                            rules={[{ required: true, message: '请输入日程名称' }]}
                                                        >
                                                            <Input

                                                                placeholder="请输入日程名称" className='activityPlan-box-card-input' />
                                                        </Form.Item>
                                                        <Form.Item
                                                            {...field}
                                                            name={[field.name, 'last']}
                                                            fieldKey={[field.fieldKey, 'last']}
                                                            rules={[{ required: true, message: '请选择日程时间' }]}
                                                        >
                                                            <DatePicker
                                                                placeholder="请选择日程时间"
                                                                className='activityPlan-box-card-input'
                                                                style={{ width: "200px" }} />
                                                        </Form.Item>
                                                        <DeleteOutlined
                                                            style={{ color: "red" }}
                                                            onClick={() => remove(field.name)} />
                                                    </Space>
                                                ))}
                                                <Form.Item>
                                                    <Button
                                                        type="dashed"
                                                        onClick={() => add()}
                                                        block
                                                        icon={<PlusOutlined />}
                                                        className='activityPlan-box-card-input'>
                                                        添加
                                                    </Button>
                                                </Form.Item>
                                            </>
                                        )}

                                    </Form.List>
                                </Form.Item>
                            </Col>
                        </Row>
                        <Col span={10}>
                            {
                                current == 1 && (
                                    <Space>
                                        <Button
                                            type="primary"
                                            style={{ background: "#1a267b" }}
                                            onClick={() => { form.submit(); next() }}
                                        >
                                            下一步
                                    </Button>
                                        <Button>预览</Button>
                                        <Button>保存草稿</Button>
                                    </Space>
                                )
                            }
                            {/* {
                                current == 3 && (
                                    <Space>
                                        <Button
                                            type="primary"
                                            htmlType="submit"
                                            from="activityFrom"
                                        >发布</Button>
                                        <Button
                                            htmlType="submit"
                                            style={{ background: "#1a267b" }}
                                            onClick={() => prev()}
                                        >上一步</Button>
                                        <Button>预览</Button>
                                        <Button>保存草稿</Button>
                                    </Space>
                                )
                            } */}
                        </Col>
                    </Form>
                </Card>
            </div>
            <div className={fromShow ? 'fromIsShow ' : 'steps-content'} >
                <Card>
                    <Descriptions
                        span={5}
                        title="选择你想要创建的活动(可多选)"
                    ></Descriptions>
                    <Space>
                        {
                            choices.map((v, i) => (
                                <div
                                    key={v.id}
                                    className={v.active ? 'active activity-item' : 'activity-item'}
                                    onClick={() => changeSelect(v.id, i)}
                                >
                                    <img src={x}
                                        key={i}
                                        className={v.active ? 'activity-item-close' : 'activity-item-close-show'} />
                                    {v.title}
                                </div>
                            ))
                        }
                    </Space>
                </Card>
                {
                    newchoice.map((v, i) => (
                        <div
                            style={{
                                width: "100%",
                                backgroundColor: '#fff',
                                height: "100%",
                                padding: "30px",
                                borderRadius: "20px"
                            }}
                            key={i}
                        >

                            <Collapse
                                style={{ width: "1100px" }}
                                key={i}
                                bordered={false}
                                defaultActiveKey={[1, 2, 3, 4, 5]}
                                expandIcon={({ isActive }) => {
                                    return (
                                        <div
                                            style={{
                                                marginRight: "24px"
                                            }}
                                        >
                                            <span style={{
                                                fontWeight: "400",
                                                color: "#1a267b",

                                            }}>{isActive ? '收起' : '展开'}</span>
                                            <CaretRightOutlined rotate={isActive ? 90 : 0} />
                                        </div>
                                    )

                                }}
                                expandIconPosition="right"
                                className="site-collapse-custom-collapse"
                            >
                                <Panel header={v.title}
                                    key={i}
                                    className="site-collapse-custom-panel"
                                    onChange={() => { panelChange }}
                                >
                                    {v.context}
                                </Panel>
                            </Collapse>
                        </div>
                    ))
                }
                <Space
                    style={{
                        marginTop: "40px"
                    }}
                >
                    <Button
                        type="primary"
                        htmlType="submit"
                        from="activityFrom"
                    >发布</Button>
                    <Button
                        onClick={() => prev()}
                    >上一步</Button>
                    <Button>预览</Button>
                    <Button>保存草稿</Button>
                </Space>
            </div>
        </div >
    )

}

export default ActivityPlan

